package cn.eleme.meal.task;
import cn.eleme.meal.excelModel.ShopModel;
import cn.eleme.meal.utils.ExcelUtils;
import cn.eleme.meal.utils.OperationUtils;
import cn.eleme.meal.utils.StrUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class ELeMeTask {

    @Autowired
    private OperationUtils operationUtils ;
    @Value("${eleme.param.outTime}")
    private Long outTime ;

    @Value("${xxxpassword}")
    String password;
    String ksid = null; //登录凭证
    @Scheduled(cron = "0/30 * * * * ?")
    public void makeMeal(){

        //读取订单信息

        System.out.println("开始查询订单........");

        Map<String,Object> query = new HashMap<>() ;
        query.put("requestId","BAE2D0747E77471EBAD595133951056F|1617001942164") ;
        List<ShopModel> shopExcelInfomaation = ExcelUtils.getShopExcelInfomaation();

        for (ShopModel shopModel : shopExcelInfomaation){
            query.put("shopId",shopModel.getShopId()) ;
            ksid = "MDCYZMMTA1Mjc0Mjg4MjUxNzAxTmFOTU8xZjRQ";
            query.put("ksid",ksid);
            if (!org.springframework.util.StringUtils.isEmpty(shopModel.getLastUseTime())) {
                SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    if (System.currentTimeMillis() > formatter2.parse(shopModel.getLastUseTime()).getTime()) {
                        System.out.println("软件授权已经到期，请重新购买");
                        return;
                    }
                } catch (ParseException e) {
                    System.out.println("解析到期时间报错" + e);
                }
            }
            String orderInfo = operationUtils.readListInfo(query) ;
            //提取数据
            if (StringUtils.isBlank(orderInfo)){
                return;
            }


            //清理大片空格
            //去除NUL域
            orderInfo = StrUtils.delNulStr(orderInfo) ;
            JSONObject jsonObject = JSONObject.fromObject(orderInfo) ;
            System.out.println("请求查询接口返错误信息 {} " + jsonObject.getString("error"));
            if (jsonObject.containsKey("result")) {
                JSONObject result = jsonObject.getJSONObject("result");
                if (result.containsKey("orders")) {
                    JSONArray orders = result.getJSONArray("orders");
                    orders.stream().filter(o->{
                        JSONObject oJson = JSONObject.fromObject(o) ;
                        String activeTime = oJson.getString("activeTime") ;
                        Long nowSeconds = System.currentTimeMillis()/1000 ;
                        // 根据当前时间计算出餐时间
                        outTime = calculationOrderTime(shopModel);
                        boolean timeOut = true ;
                        try {
                            Date activeTimeDate = DateUtils.parseDate(activeTime, "yyyy-MM-dd'T'HH:mm:ss");
                            Long activtSeconds = activeTimeDate.getTime()/1000 ;
                            if (activtSeconds+outTime>nowSeconds){
                                timeOut = false ;
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        return "ARRIVED".equals(oJson.getString("state")) && "SUCCESS".equals(oJson.getString("paymentStatus")) && timeOut;
                    }).forEach(e -> {
                        System.out.println(e.toString());
                        JSONObject orderJSON = JSONObject.fromObject(e) ;
                        String orderId = orderJSON.getString("id") ;
                        System.out.println("下单订单号为{} :" + orderId + "商品名称为{} :" + orderJSON.getString("shopName"));
                        // TODO 添加需要的参数
                        operationUtils.clickButton(orderJSON,jsonObject, ksid);
                    });
                }
            }
        }



    }

    /**
     * 根据当前时间计算出餐时间
     * 判断当前时间在哪个时间段区间内
     * @param shopModel 店铺信息
     * @return 返回当前时间段出餐时间
     * */
    private Long calculationOrderTime(ShopModel shopModel) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
        Date currentTime = new Date();
        try {
            // 早餐时间
            String breakFastTime = shopModel.getBreakFastTime();
            String[] breakFastTimeSplit = breakFastTime.split("-"); //
            // 早高峰开始时间
            Date breakFastStartDate = df.parse(df1.format(currentTime) + " " + breakFastTimeSplit[0] + ":00"); //早高峰开始时间
            Date breakFastEndDate = df.parse(df1.format(currentTime) + " " + breakFastTimeSplit[1] + ":00");//早高峰结束时间
            if (currentTime.after(breakFastStartDate) && currentTime.before(breakFastEndDate)){ // 早高峰区间段
                return Long.parseLong(shopModel.getBreakFastOrderTime());
            }

            // 午餐时间
            String lunchTime = shopModel.getLunchTime();
            String[] lunchTimeSplit = lunchTime.split("-");
            Date lunchTimeStartDate = df.parse(df1.format(currentTime) + " " + lunchTimeSplit[0]+ ":00"); //早高峰开始时间
            Date lunchTimeEndDate = df.parse(df1.format(currentTime) + " " + lunchTimeSplit[1] + ":00");//早高峰结束时间
            if (currentTime.after(lunchTimeStartDate) && currentTime.before(lunchTimeEndDate)){ // 早高峰区间段
                return Long.parseLong(shopModel.getLunchOrderTime());
            }

            //晚高峰开始时间
            String dinnerTime = shopModel.getDinnerTime();
            String[] dinnerTimeSplit = dinnerTime.split("-");
            Date dinnerTimeStartDate = df.parse(df1.format(currentTime) + " " +dinnerTimeSplit[0]+ ":00"); //早高峰开始时间
            Date dinnerTimeEndDate = df.parse(df1.format(currentTime) + " " + dinnerTimeSplit[1] + ":00");//早高峰结束时间
            if (currentTime.after(dinnerTimeStartDate) && currentTime.before(dinnerTimeEndDate)){ // 早高峰区间段
                return Long.parseLong(shopModel.getDinnerOrderTime());
            }

        } catch (ParseException e) {
            System.out.println("解析高峰时间报错,请检查日期字段");
        }
        return Long.parseLong(shopModel.getCommonOrderTime());
    }

    public static void main(String[] args) {
        new ELeMeTask().makeMeal();
    }
}
